<?php

namespace app\common\service;

use app\common\model\UserModel;

class UserService
{
    public function login($phone, $password)
    {
        $db   = new UserModel();
        $info = $db->where('phone', $phone)->find();
        if (!$info) {
            return json(['code' => 1, 'msg' => '暂无此用户']);
        }
        if ($info['password'] != md5($password)) {
            return json(['code' => 1, 'msg' => '账号或者密码有误']);
        }
        session('uid', $info['id']);
        session('username', $info['username']);
        return json(['code' => 0, 'msg' => '登录成功']);
    }

    public function reg($data)
    {
        $db  = new UserModel();
        $res = $db->save($data);
        if ($res) {
            $info = $db->where('phone', $data['phone'])->find();
            session('uid', $info['id']);
            session('username', $info['username']);
            return json(['code' => 0, 'msg' => '注册成功']);
        } else {
            return json(['code' => 1, 'msg' => '注册失败']);
        }
    }

    public function _info($id)
    {
        $db   = new UserModel();
        $info = $db->where('id', $id)->find();
        return json(['code' => 0, 'msg' => '获取成功', 'data' => $info]);
    }

    public function _list($page, $limit)
    {
        $db    = new UserModel();
        $list  = $db->page($page)->limit($limit)->select();
        $count = $db->count('id');
        return json(['code' => 0, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
    }
}
